package 比较;

import java.util.concurrent.atomic.AtomicInteger;

public class test1 {
    private AtomicInteger counter = new AtomicInteger(0);

    public void increment() {
        for (int i = 0; i < 5000; i++) {
            counter.incrementAndGet(); // 原子操作
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public int getCounter() {
        return counter.get();
    }

    public static void main(String[] args) throws InterruptedException {
        test1 example = new test1();

        // 创建两个线程
        Thread thread1 = new Thread(() -> example.increment());
        Thread thread2 = new Thread(() -> example.increment());

        thread1.start();
        thread2.start();

        // 等待线程执行完成
        thread1.join();
        thread2.join();

        // 输出结果
        System.out.println("Final counter value: " + example.getCounter());
        String s = "hello world";
    }
}
